import sys
from PyQt6.QtWidgets import QApplication, QStackedLayout,QMainWindow,QWidget,QSplitter,QVBoxLayout
from PyQt6.QtWidgets import QPushButton,QFileDialog
from PyQt6.QtWidgets import QSizePolicy,QMessageBox,QMenuBar,QMenu
from PyQt6.QtCore import Qt,QTimer,QMetaObject,QSize,QCoreApplication,QRect
from PyQt6.QtGui import QIcon, QPixmap,QAction
from datetime import datetime
from views.LeftFileListAreaView import LeftFileListAreaView
from views.MiddlePrePdfAreaView import MiddlePrePdfAreaView
from views.RightSettingAreaView import RightSettingAreaView
from utils.Logger import LogPrint
import os
from views.WaitPromptBox import WaitPromptBox
##如果使用pyinstall打包，打开下面这段代码
import pyi_splash
from utils import ImageUtils

 
class Ui_MainWindow(QMainWindow):
    """主窗体类"""
    def __init__(self):


        """构造函数"""
        super(Ui_MainWindow,self).__init__()        # 调用父类初始化函数，需要调用父类初始化才能正常使用父类定一的变量

        #是否选中合成长图
        self.isComplex=False
        #选中的pdf文件路径列表
        self.selectedPdfList=[]#['D:/历史学科.pdf']
        #最近选中的pdf文件路径
        self.latestSelectPdfPath=''#'D:/历史学科.pdf'

        self.overallWindowWidth=800
        self.overallWindowHeight=500

        # 其他代码块
        self.setWindowFlag(Qt.WindowType.MSWindowsFixedSizeDialogHint)
        self.setupUi(self)

        

    def setupUi(self, MainWindow):
        MainWindow.setWindowTitle("PDF转图片")
        MainWindow.resize(self.overallWindowWidth, self.overallWindowHeight)

        self.setupMenuBar()

        self.setupCentralWidget()
        self.setupStatusBar()
        LogPrint.info('Ui_MainWindow init finish')
        #用于自动连接信号和槽的方法。它会查找对象的所有属性，
        # 如果属性名称符合特定的命名规则（即以 "on_" 开头），
        # 那么会尝试将该属性自动与相应的信号连接起来。
        QMetaObject.connectSlotsByName(MainWindow)

    #菜单栏
    def setupMenuBar(self):

        self.menubar = QMenuBar(parent=self)
        self.menubar.setGeometry(QRect(0, 0, self.overallWindowWidth, 22))
        self.menubar.setObjectName("menubar")
        self.menu = QMenu(parent=self.menubar)
        self.menu.setObjectName("menu")
        self.menubar.addMenu(self.menu)

        self.setMenuBar(self.menubar)

        _translate = QCoreApplication.translate
        self.menu.setTitle(_translate("MainWindow", "帮助"))

        #增加子菜单
        self.action = QAction(parent=self)
        icon1 = QIcon()
        icon1.addPixmap(ImageUtils.getQPixmap("icon_intro.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action.setIcon(icon1)
        self.action.setObjectName("menu_intro")
        self.action.setText('功能介绍')
        self.action_2 = QAction()
        icon2 = QIcon()
        icon2.addPixmap(ImageUtils.getQPixmap("icon_about.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_2.setIcon(icon2)
        self.action_2.setObjectName("menu_about")
        self.action_2.setText('关于')

        self.menu.addAction(self.action)
        self.menu.addAction(self.action_2)

        #菜单绑定点击事件
        self.menu.triggered.connect(self.onMenuClicked)
    ###菜单点击事件
    def onMenuClicked(self,m):
        if m.objectName()=="menu_intro":
            QMessageBox.information(None,'功能介绍','1、支持pdf按每页转图片功能\n2、支持整个pdf按每页合成一张图片\n3、支持多个pdf按合成一张长图片')
        elif m.objectName()=="menu_about":
            QMessageBox.information(None,'关于','版本号:1.0')
        
    ####
    ####主界面显示区域
    ####
    def setupCentralWidget(self):

        widget=QWidget()
        self.stackedLayout = QStackedLayout()  # 创建堆叠布局  
        self.stackedLayout.addWidget(self.setupAddFileWidget())
        self.stackedLayout.addWidget(self.setupOperaterFileWidget())
        self.stackedLayout.setCurrentIndex(0)
        widget.setLayout(self.stackedLayout )

        self.setCentralWidget(widget)

    def setupOperaterFileWidget(self):

        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.setSizes([200, 100])


        self.leftWidget=LeftFileListAreaView()
        self.leftWidget.setFixedSize(QSize(200,self.overallWindowHeight))
        self.leftWidget.setOnSelectedFileChangeListener(self.onSelectedFileChangeListener)


        self.middleWidget=MiddlePrePdfAreaView(selectedPdfList=self.selectedPdfList,
                                          latestSelectPdfPath=self.latestSelectPdfPath,
                                          isCombineLargeImage=False)
        self.middleWidget.setFixedHeight(self.overallWindowHeight)

        #右边布局
        self.rightWidget=RightSettingAreaView()
        self.rightWidget.setFixedHeight(self.overallWindowHeight)
        self.rightWidget.setOnRightAreaSettingChangeListener(self.onRightAreaSettingChangeListener)
        self.rightWidget.setOnShowMessage(self.onShowMessage)
        #整体布局
        splitter.addWidget(self.leftWidget)
        splitter.addWidget(self.middleWidget)
        splitter.addWidget(self.rightWidget)
        splitter.setChildrenCollapsible(False)
        splitter.setStretchFactor(0,2)
        splitter.setStretchFactor(8,1)
        #self.setCentralWidget(splitter)

        return splitter

        

    def setupAddFileWidget(self):

        widget=QWidget()
        #添加文件布局
        addFileLayout=QVBoxLayout()
        addFileLayout.setAlignment(Qt.AlignmentFlag.AlignHCenter)
      
        self.btnIcon = QPushButton(parent=self) 
        self.btnIcon.setFlat(True)
        self.btnIcon.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
        self.btnIcon.setFixedSize(QSize(80, 80))
        # 设置按钮的样式表
        btnNormalBackground=ImageUtils.getImageStyleURI('icon_btn_add.png')
        btnPressBackground=ImageUtils.getImageStyleURI('icon_btn_add_press.png')
        #styleSheet="QPushButton {border-image: url"+f"({btnNormalBackground}); "+"}"
        styleSheet=f"QPushButton {{ border-image: url({btnNormalBackground}); }}"
        styleSheet+=f"  QPushButton:pressed {{ border-image: url({btnPressBackground}); }}"
        print(styleSheet)
        self.btnIcon.setStyleSheet(styleSheet)
            
            # "QPushButton:pressed { "
            #     f"border-image: url({btnPressBackground}); "
            # "}"

        self.btnIcon.clicked.connect(self.onClickedBtnAddFile)
        addFileLayout.addWidget(self.btnIcon)

        widget.setLayout(addFileLayout)
        

        return widget
    
    #左侧文件列表改变
    def onSelectedFileChangeListener(self,selectedPdfList,latestSelectPdfPath):
        LogPrint.info(selectedPdfList,latestSelectPdfPath)
        if latestSelectPdfPath is None or selectedPdfList is None or len(selectedPdfList)==0:
            self.middleWidget.cleanPdfPreLayout()
            self.rightWidget.setSelectedPdfList(None)
        else :
            self.middleWidget.setPdfPreLayout(selectedPdfList=selectedPdfList,
                                            latestSelectPdfPath=latestSelectPdfPath)
            self.rightWidget.setSelectedPdfList(selectedPdfList)
    

    #右侧设置区域变化通知
    def onRightAreaSettingChangeListener(self,isCombineLargeImage=None,
                                         selectAllPageNo=None,
                                         selectPageNoList=None):
        LogPrint.info(isCombineLargeImage,selectAllPageNo,selectPageNoList)
        if isCombineLargeImage is not None:
            self.middleWidget.setPdfPreLayout(isCombineLargeImage=isCombineLargeImage)
        if selectPageNoList:
            self.middleWidget.setPdfPreLayout(selectPageNoList=selectPageNoList)
        if selectAllPageNo is not None:
            if selectAllPageNo==True:
                self.middleWidget.setPdfPreLayout(selectAllPageNo=True)

    #没有文件界面时，点击增加文件
    def onClickedBtnAddFile(self,event):
        #使用 QFileDialog 打开一个目录对话框，并获取选择的目录路径
        desktopPath=os.path.join(os.path.expanduser("~"),'Desktop')
        if desktopPath is None:   
            desktopPath='c:/'
        filename = QFileDialog.getOpenFileName(self, "选择文件", desktopPath,"*.pdf")
        if filename and filename[0] != '':
            LogPrint.info(filename)  # 打印选择的目录路径
            
            self.stackedLayout.setCurrentIndex(1)
            filePath=filename[0]
            #设置左中右三部分数据
            self.leftWidget.setListItem(filePath)
            self.selectedPdfList.clear()
            self.selectedPdfList.append(filePath)
            self.latestSelectPdfPath=filePath
            self.middleWidget.setPdfPreLayout(selectedPdfList=self.selectedPdfList,
                                                latestSelectPdfPath=self.latestSelectPdfPath)
            self.rightWidget.setSelectedPdfList(self.selectedPdfList) 



    #状态栏显示当前时间
    def setupStatusBar(self):
        self.statusbar = self.statusBar()
        self.statusbar.showMessage("时间准备就绪")
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000)  # 每秒更新一次

    def update_time(self):
        # 当前日期时间
        now = datetime.now()
        
        # 格式化日期时间
        formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
        time_string = "当前时间: {}".format(formatted_date)
        self.statusbar.showMessage(time_string, 0)

    def onShowMessage(self,errMsg):
        QMessageBox.warning(None,'系统错误',errMsg)

    

def main():
    ##如果使用pyinstall打包，打开下面这段代码
    try:           
        pyi_splash.close()
    except ImportError:
        pass
    ###
    app = QApplication(sys.argv)
    main = Ui_MainWindow()
    main.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()